#include<iostream>
using namespace std;
  struct TreeNode {
      int val;
      TreeNode *left;
      TreeNode *right;
      TreeNode() : val(0), left(nullptr), right(nullptr) {}
      TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
      TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
  };
 
class Solution {
public:
    int ans = -1001;
    int singlemax(TreeNode* root) {
        if (root == nullptr)
            return 0;
        int l = max(0, singlemax(root->left)), r = max(0, singlemax(root->right));
        ans = max(ans, l + r + root->val);
        return max(l, r) + root->val;
    }
    int maxPathSum(TreeNode* root) {
        singlemax(root);
        return ans;
    }
};